const { Controller } = require('egg');

class UserController extends Controller {
  async index() {

    // const { ctx } = this;
    // console.log(this);
    console.log(this.ctx.header);
    // 执行控制器
    const { service } = this;
    const userList = await service.user.getUserList();
    this.ctx.body = {
      code: 200,
      msg: '查询成功',
      data: userList,
    };
  }
  // 新增用户
  async create() {
    try {
      const { service } = this;
      const data = this.ctx.request.body;
      await service.user.addUser(data);
      if (data.username && data.password) {
        this.ctx.body = {
          code: 200,
          msg: '新增用户成功',
        };
      } else {
        this.ctx.body = {
          code: 400,
          msg: '用户或密码未输入',
        };
      }
    } catch (error) {
      this.ctx.body = {
        code: 500,
        msg: '新增用户失败',
      };
      throw error;
    }
  }
  async update() {
    const { ctx, service } = this;
    const id = ctx.params.id;
    const data = ctx.request.body;
    const updateRes = await service.user.updateUser(data, id);
    // console.log(updateRes);
    this.ctx.body = {
      code: 200,
      msg: '数据修改成功',
      data: updateRes,
    };
  }
  async destroy() {
    try {
      const id = this.ctx.params.id;
      console.log(id);
      const delUser = await this.ctx.service.user.deleteUser(id);
      if (delUser) {
        this.ctx.body = {
          code: 200,
          msg: '删除用户成功',
        };
      } else {
        this.ctx.body = {
          code: 200,
          msg: '无此用户信息，删除用户失败',
        };
      }

    } catch (error) {
      this.ctx.body = {
        code: 400,
        msg: '删除用户失败',
      };
    }
  }
}

module.exports = UserController;
